import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import {
  getToken,
  getTokenTime,
  getrefreshToken,
  getrefreshtokenTime,
} from "@/utils/auth";
import { gotoLogin } from "@/utils/index";

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

/**
 * 处理 Token 和时间的逻辑
 * @param {Object} config - axios 请求配置
 * @returns {Promise<Object>} 处理后的请求配置
 */
async function handleTokenLogic(config) {
  console.log("handleTokenLogic");
  const Token = store.getters.token;
  const refreshToken = store.getters.refreshToken;
  const tokenTime = getTokenTime();
  const refreshTokenTime = getrefreshtokenTime();

  if (Token && refreshToken && tokenTime && refreshTokenTime) {
    const nowTime = Math.floor(Date.now() / 1000);
    console.log(nowTime, tokenTime);
    console.log("handleTokenLogic1");
    if (nowTime < tokenTime) {
      // Token 有效，正常流程
      console.log("handleTokenLogic2");
      config.headers["Authorization"] = "Bearer " + getToken();
      return config;
    } else if (nowTime > tokenTime && nowTime < refreshTokenTime) {
      // Token 过期，但 Refresh Token 有效，刷新 Token 后继续请求
      console.log("handleTokenLogic3");
      try {
        await store.dispatch("user/refreshToken");
        config.headers["Authorization"] = "Bearer " + getToken();
        return service(config); // 重新发送请求
      } catch (error) {
        // 刷新 Token 失败，跳转登录
        gotoLogin();
        return Promise.reject(error);
      }
    } else if (nowTime > refreshTokenTime) {
      console.log("handleTokenLogic4");
      // Token 和 Refresh Token 都过期，跳转登录
      gotoLogin();
      return Promise.reject(new Error("Token and Refresh Token expired"));
    }
  } else {
    console.log("handleTokenLogic5");
    // 未找到 Token 或 Refresh Token，跳转登录
    gotoLogin();
    return Promise.reject(new Error("No Token or Refresh Token found"));
  }
}

// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    // 判断是否需要 Token
    const notNeedToken = config.headers.notNeedToken;
    if (notNeedToken) {
      delete config.headers.notNeedToken;
      return config;
    }

    // 处理 Token 逻辑
    return handleTokenLogic(config);
  },
  (error) => {
    console.log("Request Error:", error); // 调试用
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.status === 200) {
      if (res.success) {
        return res;
      } else {
        // 服务器返回成功状态但业务逻辑失败
        Message({
          message: res.message || "Error",
          type: "error",
          duration: 5 * 1000,
        });
        return Promise.reject(new Error(res.message || "Error"));
      }
    } else {
      // 其他状态码统一处理
      return Promise.reject(
        new Error("Request failed with status code " + response.status)
      );
    }
  },
  async (error) => {
    const response = error.response;
    const config = error.config;

    if (response) {
      switch (response.status) {
        case 401:
        case 403:
        case 405:
          // 处理 Token 逻辑并重新发送请求
          try {
            const newConfig = await handleTokenLogic(config);
            return newConfig;
          } catch (error) {
            return Promise.reject(error);
          }

        default:
          // 其他状态码的错误处理
          Message({
            message: error.message ?? "错误",
            type: "error",
            duration: 5 * 1000,
          });
          return Promise.reject(error);
      }
    } else {
      // 请求未发送出去的错误处理（如网络问题）
      Message({
        message: error.message ?? "错误",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(error);
    }
  }
);

export default service;
